<!--
*  2021-03-15
*  库存出库
-->
<template>
  <div id="app" class="material-out">
    <!-- 头部导航 -->
    <van-nav-bar title="原料投料出库" left-text="返回" left-arrow @click-left="backFn" style="color: #36d04b">
      <template #right>
        <span @click="scanFn"><van-icon name="plus" size="20" /></span>
      </template>
    </van-nav-bar>

    <!-- BODY -->
    <div style="padding: 1vh 2vw;height: 90vh;overflow: auto">
      <!-- 投料计划 -->
      <div style="font-size: 1.2rem">
        <van-row v-if="feedPlan.id > 0" style="color: #e65b3c">
          <van-col :span="9">
            <span>车间:{{feedPlan.workshopName}}</span>
          </van-col>
          <van-col style="margin-top: 0.5vh" :offset="3" :span="12">
            <span>{{feedPlan.createAt}}</span>
          </van-col>
        </van-row>
        <div v-if="feedPlan.id > 0" style="height: 1px;background-color: #e65b3c;margin: 0.5vh 0vw;"></div>
        <van-row v-if="feedPlan.yarnId > 0">
          <van-col>
            <span style="color:#0134b6">细纱编号:{{ feedPlan.yarnNo }}</span>
          </van-col>
        </van-row>
        <van-row v-if="feedPlan.yarnId > 0">
          <van-col :span="12">
            <span>批次: {{ feedPlan.yarnLotNo }}</span>
          </van-col>
          <van-col :span="12">
            <span>计划量: {{ feedPlan.yarnExpectNum }}</span>
          </van-col>
        </van-row>

        <van-row v-if="feedPlan.thickYarnId > 0">
          <van-col>
            <span style="color:#01b649">粗纱颜色:{{ feedPlan.thickYarnNo }}</span>
          </van-col>
        </van-row>
        <van-row v-if="feedPlan.thickYarnId > 0">
          <van-col :span="12">
            <span>批次: {{ feedPlan.thickYarnLotNo }}</span>
          </van-col>
          <van-col :span="12">
            <span>计划量: {{ feedPlan.thickYarnExpectNum }}</span>
          </van-col>
        </van-row>

        <van-row v-if="feedPlan.materialId > 0">
          <van-col>
            <span style="color:#85771b">色毛名称:{{ feedPlan.materialNo }}</span>
          </van-col>
        </van-row>
        <van-row v-if="feedPlan.materialId > 0">
          <van-col :span="12">
            <span>批次: {{ feedPlan.materialLotNo }}</span>
          </van-col>
          <van-col :span="12">
            <span>计划量: {{ feedPlan.materialExpectNum }}</span>
          </van-col>
        </van-row>

        <div v-if="feedPlan.id > 0" style="height: 1px;background-color: #e65b3c;margin: 1vh 0vw 0vh 0vw;"></div>
      </div>

      <!-- 已扫元素 -->
      <div style="font-size: 1.1rem">
        <van-swipe-cell style="margin-top:1vh;" :style="(usage.checker != '') ? '' : 'background-color: #b4570f'" v-for="(usage, index) in usageList">
          <template #default>
            <van-row @click="openPackWinFn(feedPlan, usage)">
              <van-col style="font-size: 1.2rem;font-weight: bolder" :span="24">
                <span :style="usageTypeStyleFn(usage)">{{ feedTypeEnum(usage.type) }}:{{ usage.refName }}</span>
              </van-col>
            </van-row>
            <van-row>
              <van-col :span="10">
                <span>批次:{{ usage.refLotNo }}</span>
              </van-col>
              <van-col :span="7">
                <span>占比:{{ usage.percent }}%</span>
              </van-col>
              <van-col :span="7">
                <span>计划量:{{usage.expectNum}}</span>
              </van-col>
            </van-row>
            <van-row>
              <van-col style="border-bottom: 1px solid #282828" :span="9" @click="showAreaPickerFn(usage)">
                <span></span><input placeholder="区域" v-model="usage.area" style="width: 35vw;height:25px;font-size: 1.3rem;font-weight: bolder;color: blue" readonly />
              </van-col>
              <van-col :span="8">
                <span style="margin-right: 1vw;"></span><input :readonly="usage.existsFlag" placeholder="重量" v-model="usage.num" style="width: 25vw;height:25px;font-size: 1.3rem;font-weight: bolder;color: red;" />kg
              </van-col>
              <van-col :span="6" v-if="usage.type == 1 || usage.type == 4">
                <span style="margin-right: 1vw;"></span><input :readonly="usage.existsFlag" placeholder="包数" v-model="usage.packageNum" style="width: 18vw;height:25px;font-size: 1.3rem;font-weight: bolder;color: #ff9100;" />包
              </van-col>
              <van-col :span="6" v-if="usage.type == 3">
                <span style="margin-right: 1vw;"></span><input :readonly="usage.existsFlag" placeholder="筒管数" v-model="usage.packageNum" style="width: 18vw;height:25px;font-size: 1.3rem;font-weight: bolder;color: #ff9100;" />个
              </van-col>
            </van-row>
            <van-row>
              <van-col :span="18">
                <span style="font-size: 1rem;">领料时间: {{ usage.createAt }}</span>
              </van-col>
              <van-col :offset="1" :span="5">
                <span style="font-size: 1rem;">{{usage.checker}}</span>
              </van-col>
            </van-row>
          </template>
          <template #right>
            <div style="display: flex;flex-flow: column;height: 100%;">
              <van-button square text="删除" type="danger" @click="delMaterialOut4FeedPickFn(usage, index)"></van-button>
              <van-button v-if="usage.type != 3 && usage.checker == ''" square text="出库确认" type="warning" @click="confirmOutFn(usage)"></van-button>
            </div>
          </template>
        </van-swipe-cell>
      </div>
    </div>

    <!-- 底部确认按钮 -->
    <div v-if="usageList.length > 0" style="padding: 1vh 2vw;display: flex">
      <van-button style="flex: 1;" type="primary" @click="confirmPickFn">确认领料</van-button>
    </div>

    <!-- 区域选择 -->
    <van-popup v-model="area.showAreaPicker" :close-on-click-overlay="false" position="bottom">
      <van-picker show-toolbar value-key="label" :columns="area.areaColumns" @confirm="selectAreaFn" @cancel="area.showAreaPicker = false"></van-picker>
    </van-popup>

    <!-- 全屏遮罩 -->
    <van-overlay v-show="scanWorkerFlag" @click="scanWorkerFlag = false">
      <template>
        <div style="height:100vh; display: flex; flex-flow:column; justify-content: center;align-items: center">
          <van-loading color="#1989fa" size="80"></van-loading>
          <div><span style="color: #1989fa;font-size: 2rem;">请扫员工码</span></div>
          <div><span style="color: #fa6f19;font-size: 1.2rem;">点击任意位置取消</span></div>
        </div>
      </template>
    </van-overlay>

    <!-- 粗纱包子包 -->
    <van-popup v-model="thickYarnPack.show" :close-on-click-overlay="false" style="width: 70vw;">
      <div style="padding: 1vh 2vw;">
        <van-field label="库存" label-align="right" clearable colon v-model="thickYarnPack.weight"></van-field>
        <van-field label="筒管颜色" label-align="right" colon :readonly="true" v-model="thickYarnPack.spindleColor"></van-field>
        <van-field label="筒管数" label-align="right" clearable colon v-model="thickYarnPack.spindleNum"></van-field>
        <van-field label="区域" label-align="right" colon :readonly="true" v-model="thickYarnPack.storeArea"></van-field>
        <div style="display: flex;justify-content: center; align-items: center; margin: 10px 0px;">
          <van-button style="margin-right: 2vw;" type="danger" text="取消" @click="thickYarnPack.show = false"></van-button>
          <van-button type="primary" text="确认" @click="confirmThickYarnPackFn"></van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import {
  delOut4FeedPick,
  loadFeedPlanDetail,
  loadMaterialAreaStockData,
  loadMaterialBatchDetail,
  loadThickYarnAreaStockData,
  loadThickYarnBatchDetail, loadThickYarnPackDetail,
  loadUsage4FeedPickData,
  materialCheckOut,
  out4FeedPick,
  thickYarnCheckOut
} from "@/api/feed";
import {feedTypeEnum, feedWorkshopStoreEnum, SPLIT_XHX} from "@/api/enum";
import {deepCopy, getFloat, openWin, randomStr} from "@/utils";
import {scanToLogin} from "@/api/login";
import {delMaterialPackage4PlanMaterial, loadMaterialPackByPlanMaterialData} from "@/api/material";

export default {
  name: "out4Pick",
  data() {
    return {
      /* 投料计划 */
      feedPlan: {},

      /* 已扫用料 */
      usageList: [],
      curUsage: null,

      /* 区域选择 */
      area: {
        showAreaPicker: false,
        areaColumns: []
      },

      //全屏遮罩
      scanWorkerFlag: false,   //暂时同时用于判断是否扫员工码

      /* 粗纱包子包 */
      thickYarnPack: {
        show: false,
        id: "",
        spindleColor: "",
        spindleNum: "",
        weight: "",
        storeArea: "",
        storeAreaId: "",
      }
    };
  },
  created() {
    const that = this;
    if (process.env.NODE_ENV === "production") {
      this.$nextTick(() => {
        that.initFn();
      });
    } else {
      window.apiready = function () {
        that.initFn();
      };
    }
  },
  methods: {
    feedTypeEnum,
    //初始化
    initFn() {
      const that = this;

      //监听页面消失的时候，关掉页面就可以了
      window.api.addEventListener({
        name: "viewappear",
      }, () => {
        that.usageList.forEach(usage => {
          that.fillUsageFn(usage);
        });
      });
    },
    //返回
    backFn() {
      window.api.closeWin();
    },
    //扫码
    scanFn() {
      const that = this;
      const zyHmsScan = api.require('zyHmsScan');
      zyHmsScan.openDefaultView({}, ret => {
        if(ret.status) {
          if(that.scanWorkerFlag) {   //扫员工码
            let loginIndex = ret.result.indexOf(",type=login,");
            if (loginIndex != -1) {
              let infos = ret.result.split(",type=login,");
              scanToLogin({
                no: infos[0],
                pwd: infos[1],
                platform: 3,
                captcha: randomStr(),
              }, loginRes => {
                let params = {
                  isTokenFlag: true,
                  accessToken: loginRes.accessToken,
                  userId: loginRes.userId,
                  outId: that.curUsage.outId
                };
                if(that.curUsage.type == 1 || that.curUsage.type == 4) {    //原料/色毛
                  materialCheckOut(params, res => {
                    if(res.code && res.code != 2000) {
                      that.$toast.fail(res.msg);
                    } else {
                      that.$toast.success("确认成功");
                      that.curUsage.checker = loginRes.realName;
                    }
                    that.scanWorkerFlag = false;
                  });
                } else if(that.curUsage.type == 2) {    //细纱

                } else if(that.curUsage.type == 3) {    //粗纱
                  thickYarnCheckOut(params, res => {
                    if(res.code && res.code != 2000) {
                      that.$toast.fail(res.msg);
                    } else {
                      that.$toast.success("确认成功");
                      that.curUsage.checker = loginRes.realName;
                    }
                    that.scanWorkerFlag = false;
                  });
                }
              });
            } else {
              that.$toast.fail("员工二维码异常");
            }
            return;   //返回 不执行下面的
          }

          if(ret.result.startsWith("21,")) {   //投料计划
            that.loadFeedPlanDetailFn(ret.result.substring(3), true);
          } else if(ret.result.startsWith("20,")) {    //原料 色毛 批次
            if(!that.feedPlan || !that.feedPlan.id || that.feedPlan.id <= 0) {
              that.$toast.fail("请先扫投料计划");
              return;
            }
            let batchId = ret.result.substring(3);
            if(that.usageList.some(usage => usage.refBatchId == batchId && usage.outId <= 0)) {
              that.$toast.fail("已在列表中");
              return;
            }
            loadMaterialBatchDetail(batchId, materialBatch => {
              let usage = that.feedPlan.usageList.find(usage => (usage.type == 1 || usage.type == 4) && usage.refBatchId == materialBatch.id);
              if(!usage) {
                that.$toast.fail("不能出库,不是计划内的原料");
                return;
              }
              usage.weight = materialBatch.weight;
              usage.area = "";
              usage.outId = 0;    //新扫的没有出库
              let usageCopy = deepCopy(usage);
              that.fillUsageFn(usageCopy);
              that.usageList.push(usageCopy);
            });
          } else if(ret.result.startsWith("31,")) {    //粗纱包
            if(!that.feedPlan || !that.feedPlan.id || that.feedPlan.id <= 0) {
              that.$toast.fail("请先扫投料计划")
              return;
            }
            let packId = ret.result.substring(3);
            if(that.usageList.some(usage => usage.refBatchId == packId && usage.outId <= 0)) {
              that.$toast.fail("已在列表中");
              return;
            }

            loadThickYarnPackDetail({packId: packId}, pack => {
              let usage = that.feedPlan.usageList.find(usage => usage.type == 3 && usage.refId == pack.batchId);   //ref存的就是批次
              if(!usage) {
                that.$toast.fail("不能出库,不是计划内的粗纱")
                return;
              }
              that.thickYarnPack.id = pack.id;
              that.thickYarnPack.spindleColor = pack.spindleColor;
              that.thickYarnPack.spindleNum = pack.spindleNum;
              that.thickYarnPack.weight = pack.weight;
              that.thickYarnPack.storeArea = pack.storeArea;
              that.thickYarnPack.storeAreaId = pack.storeAreaId;
              that.curUsage = usage;
              that.curUsage.areaStock = pack.areaStock;
              that.thickYarnPack.show = true;
            });
          } else {
            that.$toast.fail("请扫投料计划或者原料批次");
            return;
          }
        }
      });
    },

    // 加载计划详情
    loadFeedPlanDetailFn(planId, scanFlag) {
      const that = this;
      loadFeedPlanDetail(planId, res => {
        that.feedPlan = res;
        that.usageList.splice(0, that.usageList.length);
        //继续加载已领数据
        loadUsage4FeedPickData({planId: res.id}, data => {
          data.forEach(feedUsage => {
            feedUsage.existsFlag = true;
            that.usageList.push(feedUsage);
          });
          that.$toast({
            type: "success",
            message: "请继续扫原料批次码",
            onClose: () => {
              if(scanFlag) {
                that.scanFn();
              }
            }
          });
        });
      });
    },

    //弹出区域选择框
    showAreaPickerFn(usage) {
      const that = this;
      if(usage.outId > 0 || usage.existsFlag) {
        return;
      }
      that.curUsage = usage;
      //加载区域库存
      that.area.areaColumns.splice(0, that.area.areaColumns.length);
      if(usage.type == 1 || usage.type == 4) {   //原料区域
        loadMaterialAreaStockData({batchId: usage.refBatchId}, data => {
          data.forEach(areaNum => {
            that.area.areaColumns.push({
              label: areaNum.area + SPLIT_XHX + areaNum.stock,
              id: areaNum.id
            });
          });
          that.area.showAreaPicker = true;
        });
      } else if(usage.type == 3) {
        loadThickYarnAreaStockData({batchId: usage.refBatchId}, data => {
          data.forEach(areaNum => {
            that.area.areaColumns.push({
              label: areaNum.area + SPLIT_XHX + areaNum.stock,
              id: areaNum.id
            });
          });
          that.area.showAreaPicker = true;
        });
      }
    },

    // 选择区域
    selectAreaFn(value) {
      const that = this;
      let areaNum = value.label.split(SPLIT_XHX);
      that.curUsage.areaId = value.id;    //区域库存ID
      that.curUsage.area = areaNum[0];
      that.curUsage.areaStock = Number(areaNum[1]);   //提交时候校验用
      that.area.showAreaPicker = false;
    },

    //渲染颜色
    usageTypeStyleFn(usage) {
      if(usage.type == 1 || usage.type == 4) {
        return "color: #a87c08;";
      } else if(usage.type == 2) {
        return "color: #0134b6;";
      } else if(usage.type == 3) {
        return "color: #01b649;";
      }

      return "";
    },

    //确认领料
    confirmPickFn() {
      const that =this;
      let params = {
        planId: that.feedPlan.id,
        area: feedWorkshopStoreEnum(that.feedPlan.workshopName),    //领料目标车间临仓
        usageList: that.usageList,
      };
      params.usageList = that.usageList.filter(usage => !usage.outId || usage.outId < 0);
      if(params.usageList.length == 0) {
        that.$toast.fail("请扫物料码");
        return;
      }
      if(!params.usageList.filter(usage => usage.type == 1 || usage.type == 4).every(usage => usage.areaId > 0 && usage.packageNum > 0 && usage.num > 0)) {
        that.$toast.fail("区域/包数/重量必填");
        return;
      }
      if(!params.usageList.filter(usage => usage.type == 3).every(usage => usage.areaId > 0 && usage.num > 0)) {
        that.$toast.fail("区域/重量必填");
        return;
      }
      if(!params.usageList.every(usage => usage.num <= usage.areaStock)) {
        that.$toast.fail("库存有不足,请检查");
        return;
      }

      out4FeedPick(params, () => {
        that.$toast.success("领料成功");
        that.loadFeedPlanDetailFn(that.feedPlan.id);
      });
    },

    //删除领料记录
    delMaterialOut4FeedPickFn(usage, index) {
      const that = this;
      if(usage.type == 3 && usage.outId == 0) {   //粗纱未确认
        that.usageList.splice(index, 1);
        return;
      }
      if(usage.outId > 0) {
        delOut4FeedPick(usage, res => {
          that.usageList.splice(index, 1);
          that.$toast.success("删除投料成功");
        });
      } else {
        //删除临时包
        delMaterialPackage4PlanMaterial({
          planId: usage.planId,
          materialId: usage.refId
        }, () => {
          that.usageList.splice(index, 1);
        });
      }
    },

    //出库确认
    confirmOutFn(usage) {
      const that = this;
      if(usage.outId > 0) {
        that.curUsage = usage;
        that.scanWorkerFlag = true;
        that.scanFn();
      }
    },

    /* 打开包窗口 */
    openPackWinFn(feedPlan, usage) {
      const that = this;
      openWin("material-pack", {
        feedPlan: feedPlan,
        usage: usage
      });
    },

    /* 填充用料数据 */
    fillUsageFn(usage) {
      const that = this;
      if(usage.existsFlag) {
        return;
      }
      loadMaterialPackByPlanMaterialData({
        materialId: usage.refId,
        planId: usage.planId
      }, data => {
        if(!data.code && data.code != 0) {
          if(usage.outId > 0) {   //已收货的
            data = data.filter(pack => pack.refId == usage.outId);
          } else {
            data = data.filter(pack => pack.refId == 0);
          }
          usage.packageNum = data.length;
          usage.num = 0;
          if(data.length == 1) {
            usage.num = data[0].weight;
          } else if(data.length > 1) {
            usage.num = getFloat(data.map(pack => Number(pack.weight)).reduce((a, b) => Number(a) + Number(b)), 2);
          }
        } else if(!usage.existsFlag) {
          usage.packageNum = 0;
          usage.num = 0;
        }
        that.$forceUpdate();
      });
    },

    /* 确认粗纱包 */
    confirmThickYarnPackFn() {
      const that = this;
      that.curUsage.existsFlag = true;    //要只读
      that.curUsage.outId = 0;
      that.curUsage.num = that.thickYarnPack.weight;
      that.curUsage.packageNum = that.thickYarnPack.spindleNum;   //筒管数
      that.curUsage.packId = that.thickYarnPack.id;
      that.curUsage.area = that.thickYarnPack.storeArea;
      that.curUsage.areaId = that.thickYarnPack.storeAreaId;
      that.usageList.push(deepCopy(that.curUsage));
      that.thickYarnPack.show = false;
    }
  },
};
</script>

<style lang="scss" scoped>
.material-out {
  display: flex;
  flex-direction: column;
  .van-cell {
    .van-cell__value {
      flex: 0 0 30%;
      .van-field {
        padding: 0;
        display: flex;
        .van-cell__value {
          flex: 1;
        }
        .van-field__control {
          text-align: right;
        }
      }
    }
  }
  .store-out-btn {
    padding: 16px;
    &.van-hairline--top-bottom::after,
    .van-hairline-unset--top-bottom::after {
      border-width: 0;
    }
  }
}
</style>
